package com.xinghanlaser.applet.base.common.entity;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xinghanlaser.applet.base.common.enums.ResponseCodeEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Collections;
import java.util.List;

/**
 * Created by yyym on 2019/9/21.
 */
@Data
@Builder
public class ResponseEntity<T> {
    private int code;

    private String msg;

    private T data;

    public static <T> ResponseEntity<T> ok() {
        return ResponseEntity.<T>builder().code(ResponseCodeEnum.OK.getCode()).build();
    }

    public static <T> ResponseEntity<T> okMsg(String msg) {
        return ResponseEntity.<T>builder().code(ResponseCodeEnum.OK.getCode()).msg(msg).build();
    }

    public static <T> ResponseEntity<T> ok(T data) {
        return ResponseEntity.<T>builder().code(ResponseCodeEnum.OK.getCode()).data(data).build();
    }

    public static <T> ResponseEntity<T> ok(String msg, T data) {
        return ResponseEntity.<T>builder().code(ResponseCodeEnum.OK.getCode()).msg(msg).data(data).build();
    }


    public static <T> ResponseEntity<T> faultMsg(String msg) {
        return ResponseEntity.<T>builder().code(ResponseCodeEnum.FAULT_DEFAULT.getCode()).msg(msg).build();
    }

    public static <T> ResponseEntity<T> fault(T data) {
        return ResponseEntity.<T>builder().code(ResponseCodeEnum.FAULT_DEFAULT.getCode()).data(data).build();
    }

    public static <T> ResponseEntity<T> fault(ResponseCodeEnum code, String msg) {
        return ResponseEntity.<T>builder().code(code.getCode()).msg(msg).build();
    }

    public static <T> ResponseEntity<T> fault(ResponseCodeEnum code, String msg, T data) {
        return ResponseEntity.<T>builder().code(code.getCode()).msg(msg).data(data).build();
    }

    public static <T> ResponseEntity<PageResult<T>> okPage(IPage<T> pageResult) {
        return ResponseEntity.ok(PageResult.of(pageResult));
    }

    public static <T> ResponseEntity<PageResult<T>> okPage(PageResult<T> pageResult){
        return ResponseEntity.ok(pageResult);
    }
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class PageResult<T> {
        /**
         * 查询数据列表
         */
        private List<T> records = Collections.emptyList();

        /**
         * 总数
         */
        private long total = 0;

        public static <T> PageResult<T> of(IPage<T> page) {
            return new PageResult<>(page.getRecords(), page.getTotal());
        }
    }

}
